#!/bin/bash
#****************************************************************#
# ScriptName: elf-checker.sh
# Author: lianyihong@ieisystem.com
# Create Date: 2023-12-14 10:46
# Modify Author: lianyihong@ieisystem.com
# Modify Date: 2023-12-14 10:47
# Function:
#***************************************************************#

filename=""
auth_key="security.authorization"
auth_value="kos"

usage() {
	echo "elf-checker: A helper used to validate the legality of an ELF file during its loading process."
	echo "options: "
	echo "	-h		show help information."
	echo "	-e		enable elf-checker."
	echo "	-i		init: grant permissions for all files."
	echo "	-c [filename]	check if this file has been granted permissions."
	echo "	-g [filename]	grant permissions for this file."
	echo "	-r [filename]	revoke the permissions to this file."
	echo "	-d		disable elf-checker." 	  
}

init() {
	find / -path /proc -prune -o -path /sys -prune -o -path /dev -prune -o -path /run -prune -o -path /boot/efi -prune -o -path /boot/grub2 -prune -o -path /run/user -prune -o -type f -exec setfattr -n ${auth_key} -v ${auth_value} {} + 2>/dev/null
	echo "init successfully!"
}

check_value() {
	local result=$(getfattr -n ${auth_key} $1 2>/dev/null)
	local value="none"
	
	if [ $? -eq 0 ]; then
		value=$(echo "$result" | awk -F '"' '{print $2}' | tr -d '\n')
	fi
	
	# echo "$value"
	if [ "$value" = "kos" ]; then
		echo "The file '$filename' has been granted permissions."
	else
		echo "The file '$filename' has NOT been granted permissions."
	fi
}

while getopts 'c:g:r:edhi' OPT; do
	case $OPT in
		'h')
			usage
			exit 0
			;;
		'e')
			./elf-checker-start.sh
			exit 0
			;;
		'i')
			init
			exit 0
			;;
		'c')
			filename=$OPTARG
			check_value $filename
			exit 0
			;;
		'g')
			filename=$OPTARG
			setfattr -n $auth_key -v $auth_value $filename
            echo "Grant permission for $filename successfully!"
            exit 0
            ;;
		'r')
			filename=$OPTARG
			setfattr -x $auth_key $filename
            echo "Permissions of $filename has been revoked successfully!"
            exit 0
            ;;
		'd')
            ./elf-checker-stop.sh
			exit 0
            ;;
		*)
			usage
			exit 0
			;;
	esac
done





